package com.fz.us.oa.web.controller.com;

import com.fz.us.admin.base.utils.EntityConfig;
import com.fz.us.admin.base.utils.ModuleConfig;
import com.fz.us.admin.company.bean.FlowEnum;
import com.fz.us.admin.company.entity.TaskEntity;
import com.fz.us.admin.company.entity.User;
import com.fz.us.oa.core.entity.com.ModulePower;
import com.fz.us.oa.core.service.com.ModulePowerService;
import com.fz.us.oa.web.controller.BaseController;
import com.fz.us.oa.web.shiro.bind.annotation.CurrentUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

/**
 * Created by dzw on 2017/12/12.
 */
@Controller
@RequestMapping(value = "/com/modulePower")
public class ModulePowerController extends BaseController {
    private static final long serialVersionUID = -2726700596148657217L;

    @Autowired
    private ModulePowerService modulePowerService;

    private static final EntityConfig entityConfig = new EntityConfig();
    private static final ModuleConfig moduleConfig = new ModuleConfig();

    /**
     * 权限申请页面
     */
    @RequestMapping(value = "input", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String input(@CurrentUser User user, Model model, String reApply, String keyId){
        ModulePower modulePower;
        if("1".equals(reApply)){ //重新申请权限
            modulePower=modulePowerService.getModulePowerPassByUser(user);
            if(modulePower==null) return ajaxHtml("<div class=\"panel\"><div class=\"row\" style=\"height: 600px\">\n" +
                    "            <div class=\"col-lg-6 col-lg-offset-3\">\n" +
                    "              <div class=\"panel panel-trans text-center\">\n" +
                    "                <h3 class=\"panel-title\" style=\"margin-top: 250px;color: #9da9b6\">你好像还没有申请过权限</h3>\n" +
                    "              </div>\n" +
                    "            </div>\n" +
                    "          </div></div>");

            List<ModulePower> reModulePowerList=modulePowerService.getReModulePowerByUser(user);
            for(ModulePower reM:reModulePowerList){
                if(FlowEnum.ProcessState.Backed.equals(reM.getProcessState())){
                    reApply="0";
                    modulePower=reM;break;
                }else if(FlowEnum.ProcessState.Running.equals(reM.getProcessState())){
                    return ajaxHtml("<div class=\"panel\"><div class=\"row\" style=\"height: 600px\">\n" +
                            "            <div class=\"col-lg-6 col-lg-offset-3\">\n" +
                            "              <div class=\"panel panel-trans text-center\">\n" +
                            "                <h3 class=\"panel-title\" style=\"margin-top: 250px;color: #9da9b6\">您重新申请的权限申请正在审批中，请等待...</h3>\n" +
                            "              </div>\n" +
                            "            </div>\n" +
                            "          </div></div>");
                }
            }

        }else{ //第一次申请  或者 退回后再申请
            if(StringUtils.isNotEmpty(keyId)){
                modulePower=modulePowerService.get(keyId);
            }else{
                modulePower=modulePowerService.getModulePowerByUser(user);
            }
        }

        List<Map<String,Object>> mapList = moduleConfig.getAllProperties();
        Set<String> moduleNameSet=new HashSet<String>();
        for(Map map:mapList){
            if("系统管理".equals(map.get("value").toString())) continue;
            moduleNameSet.add(map.get("value").toString());
        }
        model.addAttribute("moduleNameSet",moduleNameSet);
        model.addAttribute("data", getInfo());
        model.addAttribute("user",user);
        model.addAttribute("reApply",reApply);
        model.addAttribute("modulePower", modulePower);
        return "/com/modulePower_input";
    }

    /**
     * 审批页面
     */
    @RequestMapping(value = "read", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String read(@CurrentUser User user, Model model, String keyId){
        if(StringUtils.isNotEmpty(keyId)){
            ModulePower modulePower=modulePowerService.get(keyId);
            model.addAttribute("modulePower",modulePower);

            String entityName="";
            List<Map<String,Object>> entityList = entityConfig.getAllProperties();
            for(String s:modulePower.getEntityName().split(",")){
                for(Map map:entityList){
                    if(s.equals(map.get("key").toString())){
                        entityName+=map.get("value").toString()+",";
                    }
                }
            }
            model.addAttribute("entityName",entityName.substring(0,entityName.length()-1));

            TaskEntity taskEntity = taskEntityService.getInfoByKeyId(modulePower.getId());
            Set<User> users = taskEntity.getEditors();
            String editor = "";
            for(User editorId:users){
                editor += editorId.getId() + ",";
            }
            if(StringUtils.isNotEmpty(editor)){
                editor = editor.substring(0, editor.length()-1);
            }
            model.addAttribute("editor", editor);
            model.addAttribute("user", user);

        }
        return "/com/modulePower_read";
    }

    /**
     * 根据模块名获取该模块下的所有表单
     */
    @RequestMapping(value = "getFormList", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Object getFormList(String moduleName){
        List<Map<String,Object>> moduleList = moduleConfig.getAllProperties();
        List<String> formKeyList=new ArrayList<String>();
        for(Map map:moduleList){
            if(map.get("value").toString().equals(moduleName)){
                formKeyList.add(map.get("key").toString());
            }
        }

        List<Map<String, Object>> data=new ArrayList<Map<String, Object>>();
        List<Map<String,Object>> entityList = entityConfig.getAllProperties();
        for(Map<String,Object> map:entityList){
            if(formKeyList.contains(map.get("key").toString())){
                data.add(map);
            }
        }
        return data;
    }

    // 提交
    @RequestMapping(value = "commit", method = RequestMethod.POST)
    public Object commit(@CurrentUser User user, String keyId, String module, String entity, String comment, Integer reApply){
        List<User> userList = modulePowerService.getManagers();
        if(userList.size()==0){
            return ajaxJson(resultService.fail("没有找到管理员"));
        }else if(userList.contains(user)){
            return ajaxJson(resultService.fail("管理员不需要申请权限"));
        }
        User editor=userList.get(0);

        ModulePower modulePower=null;
        if(reApply==null || reApply!=1){
            if(StringUtils.isEmpty(keyId)){
                modulePower=new ModulePower();
                modulePower.setCreater(user);
                modulePower.setCompany(user.getCompany());
                modulePower.setReApply(0);
            }else{
                modulePower=modulePowerService.get(keyId);
            }
        }else{ //第二次申请

            if(modulePowerService.get(keyId)==null) return ajaxJson(resultService.fail("没有找到首次申请记录"));

            modulePower=new ModulePower();
            modulePower.setCreater(user);
            modulePower.setCompany(user.getCompany());
            modulePower.setReApply(1);
            modulePower.setModulePower(modulePowerService.get(keyId));
        }
        modulePower.setEntityName(entity);
        modulePower.setModuleName(module);

        if(reApply!=null && reApply==1){
            modulePowerService.commit(modulePower, "com.fz.us.oa.core.entity.com.ModulePower", user, "1", editor);
        }else{
            if (StringUtils.isNotEmpty(keyId)) {
                modulePowerService.approve(modulePower, user, comment, "1", editor);
            } else {
                modulePowerService.commit(modulePower, "com.fz.us.oa.core.entity.com.ModulePower", user, "1", editor);
            }
        }

        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("message", "提交成功");
        rMap.put("state", "1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    //审批
    @RequestMapping(value = "approve", method = RequestMethod.POST)
    public Object approve(@CurrentUser User user, String keyId){
        Map<String,Object> rMap=new HashMap<String,Object>();
        ModulePower modulePower=modulePowerService.get(keyId);
        modulePowerService.approve(modulePower, user, "通过", "0", null);

        if(modulePower.getReApply()==1){
            ModulePower mainModulePower=modulePower.getModulePower();
            mainModulePower.setEntityName(modulePower.getEntityName());
            mainModulePower.setModuleName(modulePower.getModuleName());
            modulePowerService.update(mainModulePower);
        }

        rMap.put("message", "提交成功");
        rMap.put("state", "1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    //退回
    @RequestMapping(value = "back", method = RequestMethod.POST)
    public Object back(@CurrentUser User user, String keyId,String backStepNo, String comment) {
        if (StringUtils.isNotEmpty(keyId)) {
            ModulePower modulePower=modulePowerService.get(keyId);
            if(StringUtils.isNotEmpty(backStepNo)){
                String[] arr = backStepNo.split("\\|");
                int stepNo = Integer.parseInt(arr[0]);
                User editor = userService.get(arr[1]);
                modulePowerService.back(modulePower, comment, stepNo, editor);
            }
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("message","退回成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    @RequestMapping(value = "powerEditPage", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String powerEditPage(String userId, Model model){
        ModulePower modulePower=modulePowerService.getModulePowerPassByUser(userService.get(userId));
        model.addAttribute("data", getInfo());
        model.addAttribute("userId", userId);
        model.addAttribute("modulePower", modulePower);

        return "/com/modulePower_edit_dialog";
    }

    /**
     * 在成员管理里直接修改权限
     */
    @RequestMapping(value = "edit", method = RequestMethod.POST)
    public Object edit(String modulePowerId, String userId, String module, String entity){

        User user=userService.get(userId);
        List<ModulePower> reMList=modulePowerService.getReModulePowerByUser(user);
        for(ModulePower reM:reMList){
            if(FlowEnum.ProcessState.Running.equals(reM.getProcessState()) || FlowEnum.ProcessState.Backed.equals(reM.getProcessState())){
                return ajaxJson(resultService.fail("请先处理该成员未完成的权限申请"));
            }
        }

        if(StringUtils.isNotEmpty(modulePowerId)){
            ModulePower modulePower=modulePowerService.get(modulePowerId);
            modulePower.setModuleName(module);
            modulePower.setEntityName(entity);
            modulePowerService.update(modulePower);
            return ajaxJson(resultService.success("修改成功"));
        }else{
            if(modulePowerService.getModulePowerByUser(user)!=null){
                return ajaxJson(resultService.fail("请先处理该成员未完成的权限申请"));
            }else{
                ModulePower modulePower=new ModulePower();
                modulePower.setCreater(user);
                modulePower.setCompany(user.getCompany());
                modulePower.setModuleName(module);
                modulePower.setEntityName(entity);
                modulePowerService.commit(modulePower, "com.fz.us.oa.core.entity.com.ModulePower", user, "0", null);
                return ajaxJson(resultService.success("保存成功"));
            }
        }
    }

    /**
     * 获取所有模块表单
     */
    public List<Map<String, Object>> getInfo(){
        List<Map<String, Object>> data=new ArrayList<Map<String, Object>>();
        Map<String, Object> dataMap;
        List<Map<String, Object>> moduleList = moduleConfig.getAllProperties();
        List<Map<String, Object>> entityList = entityConfig.getAllProperties();

        Set<String> moduleNameSet=new HashSet<String>();
        for(Map<String, Object> mMap:moduleList){
            if("系统管理".equals(mMap.get("value").toString())) continue;
            moduleNameSet.add(mMap.get("value").toString());
        }

        List<Map<String, Object>> entityNameList;
        Map<String, Object> rMap;
        List<String> mKeyList;
        for(String mName:moduleNameSet){

            mKeyList=new ArrayList<String>();
            for(Map<String, Object> mMap:moduleList){
                if(mName.equals(mMap.get("value").toString())){
                    mKeyList.add(mMap.get("key").toString());
                }
            }

            dataMap=new HashMap<String, Object>();
            dataMap.put("moduleName", mName);
            entityNameList=new ArrayList<Map<String, Object>>();
            for(Map<String, Object> map:entityList){
                if(mKeyList.contains(map.get("key").toString())){
                    rMap=new HashMap<String, Object>();
                    rMap.put("entity", map);
                    entityNameList.add(rMap);
                }
            }
            dataMap.put("entityMap", entityNameList);
            data.add(dataMap);
        }

        return data;
    }
}
